<xsl:stylesheet version="1.0"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:xlink="http://www.w3.org/1999/xlink"
	xmlns:db="http://docbook.org/ns/docbook"
	xmlns:pbs="http://schema.pbs.gov.au"
	xmlns:group="http://schema.pbs.gov.au/Group#"
	xmlns:contrib="http://schema.pbs.gov.au/Contribution#"
	xmlns:xs="http://www.w3.org/2001/XMLSchema">
  
	<xsl:import href="common.xsl"/>
  
	<db:article>
		<db:info>
			<db:title>Misc Extract File</db:title>

			<db:copyright>
				<db:year>2013</db:year>
				<db:year>2012</db:year>
				<db:holder>Commonwealth of Australia</db:holder>
			</db:copyright>

			<db:legalnotice>
				<db:para>This software is copyrighted by the Commonwealth of Australia ("The Commonwealth").  The following terms apply to all files associated with the software unless explicitly disclaimed in individual files.</db:para>
				<db:para>Permission is hereby granted to use, copy, modify, distribute, and license this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. No written agreement, license, or royalty fee is required for any of the authorized uses. Modifications to this software may be copyrighted by their authors and need not follow the licensing terms described here, provided that the new terms are clearly indicated on the first page of each file where they apply.</db:para>
				<db:para>IN NO EVENT SHALL THE COMMONWEALTH OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</db:para>
				<db:para>THE COMMONWEALTH SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE COMMONWEALTH HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.</db:para>
			</db:legalnotice>

			<db:author>
				<db:personname>Steve Ball</db:personname>
				<db:email>Steve.Ball@health.gov.au</db:email>
				<db:affiliation>
					<db:orgname>Department of Health and Ageing</db:orgname>
					<db:orgdiv>PharmBiz</db:orgdiv>
				</db:affiliation>
			</db:author>
			<db:author>
				<db:personname>Daryl Maclean</db:personname>
				<db:email>Daryl.Maclean@health.gov.au</db:email>
				<db:email>d.maclean@clear.net.nz</db:email>
				<db:affiliation>
					<db:orgname>Department of Health and Ageing</db:orgname>
					<db:orgdiv>PharmBiz</db:orgdiv>
				</db:affiliation>
			</db:author>
			
			<db:revhistory>
				<db:revision>
					<db:revnumber>1.3</db:revnumber>
					<db:date>2013-02-26</db:date>
					<db:authorinitials>SRB</db:authorinitials>
					<db:revremark>Scrape EDSOF from group description.</db:revremark>
				</db:revision>
				<db:revision>
					<db:revnumber>1.2.1</db:revnumber>
					<db:date>2012-11-07</db:date>
					<db:authorinitials>DMM</db:authorinitials>
					<db:revremark>Added documentation.</db:revremark>
				</db:revision>
				<db:revision>
					<db:revnumber>1.2</db:revnumber>
					<db:date>2012-11-06</db:date>
					<db:authorinitials>SRB</db:authorinitials>
					<db:revremark>Use name for DBoF value. Synthesize value if no EDS group.</db:revremark>
				</db:revision>
				<db:revision>
					<db:revnumber>1.1</db:revnumber>
					<db:date>2012-07-17</db:date>
					<db:authorinitials>DMM</db:authorinitials>
					<db:revremark>Updated item type and category classifications, and proper matching on QNames for item memberships.</db:revremark>
				</db:revision>
				<db:revision>
					<db:revnumber>1.0</db:revnumber>
					<db:date>2012-07-13</db:date>
					<db:authorinitials>DMM</db:authorinitials>
					<db:revremark>Initial version.</db:revremark>
				</db:revision>
			</db:revhistory>
		</db:info>

		<db:para>This XSL stylesheet produces the misc extract file (<db:filename>Misc yyyymmdd.txt</db:filename>) from a PBS XML document. It only displays data that has changed since the previous months PBS XML document.</db:para>
		<db:para>The source document must be a PBS XML document.</db:para>
		<db:para>The result document is a text file.</db:para>
		<db:para>The default item delimeter is the tab character</db:para>
		<db:table>
			<db:title></db:title>
			<db:tgroup cols="4" align="left" colsep="1" rowsep="1">
				<db:colspec colnum="3" align="right"/>
				<db:thead>
					<db:row>
						<db:entry>Field Name</db:entry>
						<db:entry>Format</db:entry>
						<db:entry>Maximum Length</db:entry>
						<db:entry>Description</db:entry>
					</db:row>
				</db:thead>
				<db:tbody>
					<db:row>
						<db:entry>Item Code</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>6</db:entry>
						<db:entry>five or six characters in format (n)nnnna</db:entry>
					</db:row>
					<db:row>
						<db:entry>Start Date</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>8</db:entry>
						<db:entry>format ddmmyyyy</db:entry>
					</db:row>
					<db:row>
						<db:entry>End Date</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>8</db:entry>
						<db:entry>format ddmmyyyy</db:entry>
					</db:row>
					<db:row>
						<db:entry>Item code for associated injectable item</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>6</db:entry>
						<db:entry>When item is a solvent-injectable combo item, i.e. pbs:solvent-rule, blank otherwise. Five or six characters in format (n)nnnna.</db:entry>
					</db:row>
					<db:row>
						<db:entry>Item code for associated solvent item</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>6</db:entry>
						<db:entry>When item is a solvent-injectable combo item, i.e. pbs:solvent-rule, blank otherwise. Five or six characters in format (n)nnnna.</db:entry>
					</db:row>
					<db:row>
						<db:entry>Item type</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>2</db:entry>
						<db:entry></db:entry>
					</db:row>
					<db:row>
						<db:entry>Category code</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>2</db:entry>
						<db:entry></db:entry>
					</db:row>
					<db:row>
						<db:entry>OSPC premium flag</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>1</db:entry>
						<db:entry>'Y' is OSPC is payable, 'N' otherwise</db:entry>
					</db:row>
					<db:row>
						<db:entry>TGP premium flag</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>1</db:entry>
						<db:entry>'Y' if TGP is payable, 'N' otherwise</db:entry>
					</db:row>
					<db:row>
						<db:entry>Exemption flag</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>1</db:entry>
						<db:entry>'Y' if item is exempt from paying either OSPC or TGP, 'N' otherwise</db:entry>
					</db:row>
					<db:row>
						<db:entry>Breakable flag</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>1</db:entry>
						<db:entry>'Y' if the pack can be broken, 'N' otherwise</db:entry>
					</db:row>
					<db:row>
						<db:entry>Container Code</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>3</db:entry>
						<db:entry>'VII' if the item uses an injectable container, 'VIO' otherwise</db:entry>
					</db:row>
					<db:row>
						<db:entry>EDSOF code</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>4</db:entry>
						<db:entry>All items that are in the same Emergency Drug Supply exclusion group get the same code.</db:entry>
					</db:row>
					<db:row>
						<db:entry>Continued dispensing flag</db:entry>
						<db:entry>Character</db:entry>
						<db:entry>1</db:entry>
						<db:entry>'Y' if continued dispensing applies to this item, 'N' otherwise</db:entry>
					</db:row>
				</db:tbody>
			</db:tgroup>
		</db:table>
	</db:article>
  
	<xsl:output method="text"/>
	
	<db:param name="delimiter">
		<db:refpurpose>Field Delimiter</db:refpurpose>
		<db:para>Delimiter to use between fields. Default is tab character.</db:para>
	</db:param>
	<xsl:param name="delimiter" select="'&#x9;'"/>
	
	<db:param name="end-of-line">
		<db:refpurpose>End of Line Delimiter</db:refpurpose>
		<db:para>Delimiter to use between lines. Default is line feed character.</db:para>
	</db:param>
	<xsl:param name="end-of-line" select="'&#xa;'"/>
	
	<xsl:key name="prescribingRules" match="/pbs:root/pbs:schedule/pbs:listings-list/pbs:prescribing-rule" use="concat('#', @xml:id)"/>
	<xsl:key name="groups" match="/pbs:root/pbs:groups-list/pbs:group" use="concat('#', @xml:id)"/>
	<xsl:key name="mpps" match="/pbs:root/pbs:drugs-list/pbs:mp/pbs:mpp" use="concat('#', @xml:id)"/>
	<xsl:key name="id" match="*[@xml:id and not(ancestor-or-self::pbs:changes-list)]" use="concat('#', @xml:id)"/>
	
	<db:template name='root'>
		<db:refpurpose>Check Document Version</db:refpurpose>
		<db:para>Make sure that the source document uses the correct version of the PBS XML Schema.</db:para>
	</db:template>
	<xsl:template match="/">
		<xsl:variable name="major" select="substring-after(/*/@version, '.')"/>
		<xsl:variable name="minor" select="substring-after(/*/@version, '.')"/>

		<xsl:choose>
			<xsl:when test="$major >= 2 and $minor >= 7">
				<!-- Only want to consider prescribing rules that are a part of a change -->
				<xsl:variable name="changedRules" select="key('id', /pbs:root/pbs:changes-list/pbs:change/descendant::*[self::pbs:deletion or self::pbs:any-reference]/@xlink:href)/ancestor-or-self::pbs:prescribing-rule"/>
				
				<!-- With the way changes are recorded, multiple could appear under a prescribing rule. Ensure that each prescribing rule is only listed once  -->
				<xsl:apply-templates select="$changedRules[not(preceding-sibling::pbs:prescribing-rule/pbs:code[text() = current()/pbs:code/text()])]">
					<xsl:sort select="pbs:code"/>
				</xsl:apply-templates>
			</xsl:when>
			<xsl:otherwise>
				<xsl:message terminate='yes'>This stylesheet is designed to operate upon a Schedule XML document that conforms to version 2.7 (or later) of the PBS XML Schema.  See http://xml.pbs.gov.au/ for more information on the PBS XML Schema.</xsl:message>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>
	
	<xsl:template match="pbs:prescribing-rule">
		<xsl:param name="this" select="."/>
	
		<!-- Item code -->
		<xsl:call-template name="pad-right">
			<xsl:with-param name="text" select="$this/pbs:code"/>
			<xsl:with-param name="length" select="6"/>
		</xsl:call-template>
		<xsl:value-of select="$delimiter"/>
		
		<!-- Start date -->
		<xsl:call-template name="format-date">
			<xsl:with-param name="date" select="$this/pbs:effectivity/pbs:start"/>
		</xsl:call-template>
		<xsl:value-of select="$delimiter"/>
		
		<!-- End date -->
		<xsl:if test="$this/pbs:effectivity/pbs:non-effective">
			<xsl:call-template name="format-date">
				<xsl:with-param name="date" select="$this/pbs:effectivity/pbs:non-effective"/>
			</xsl:call-template>
		</xsl:if>
		<xsl:value-of select="$delimiter"/>
		
		<!-- Item code for associated injectable item (when item is a solvent-injectable combo item, i.e. pbs:solvent-rule, blank otherwise) -->
		<xsl:if test="$this/pbs:solvent-rule/pbs:injectable">
			<xsl:value-of select="key('prescribingRules', $this/pbs:solvent-rule/pbs:injectable/pbs:listing-reference/@xlink:href)/pbs:code"/>
		</xsl:if>		
		<xsl:value-of select="$delimiter"/>
		
		<!-- Item code for associated solvent item (as above) -->
		<xsl:if test="$this/pbs:solvent-rule/pbs:solvent">
			<xsl:value-of select="key('prescribingRules', $this/pbs:solvent-rule/pbs:solvent/pbs:listing-reference/@xlink:href)/pbs:code"/>
		</xsl:if>
		<xsl:value-of select="$delimiter"/>
	
		<!-- Item type -->
		<xsl:call-template name="determineItemType"/>
		<xsl:value-of select="$delimiter"/>
		
		<!-- Category code -->
		<xsl:call-template name="determineCategoryCode"/>
		<xsl:value-of select="$delimiter"/>
		
		<!-- OSPC premium: 'Y' is OSPC is payable, 'N' otherwise -->
		<xsl:choose>
			<xsl:when test="$this/descendant::pbs:contribution/pbs:type = 'contrib:special-patient'">Y</xsl:when>
			<xsl:otherwise>N</xsl:otherwise>
		</xsl:choose>
		<xsl:value-of select="$delimiter"/>
		
		<!-- TGP: 'Y' if TGP is payable, 'N' otherwise -->
		<xsl:choose>
			<xsl:when test="$this/descendant::pbs:contribution/pbs:type = 'contrib:therapeutic-group'">Y</xsl:when>
			<xsl:otherwise>N</xsl:otherwise>
		</xsl:choose>
		<xsl:value-of select="$delimiter"/>
		
		<!-- Exemption: 'Y' if item is exempt from paying either OSPC or TGP, 'N' otherwise -->
		<xsl:choose>
			<xsl:when test="key('groups', $this/pbs:member-of-list/pbs:member-of/@xlink:href)/pbs:type = 'group:premium-exemption'
						and not($this/descendant::pbs:contribution[pbs:type = 'contrib:special-patient' or pbs:type = 'contrib:therapeutic-group'])">Y</xsl:when>
			<xsl:otherwise>N</xsl:otherwise>
		</xsl:choose>
		<xsl:value-of select="$delimiter"/>
		
		<!-- Breakable: 'Y' if the pack can be broken, 'N' otherwise -->
		<xsl:choose>
			<xsl:when test="$this/pbs:ready-prepared/pbs:not-to-be-broken">N</xsl:when>
			<xsl:otherwise>Y</xsl:otherwise>
		</xsl:choose>
		<xsl:value-of select="$delimiter"/>
		
		<!-- Container code: 'VII' if the item uses an injectable container, 'VIO' otherwise -->
		<xsl:choose>
			<xsl:when test="key('groups', $this/pbs:member-of-list/pbs:member-of/@xlink:href)[pbs:type = 'group:container-injectable']">VII</xsl:when>
			<xsl:otherwise>VIO</xsl:otherwise>
		</xsl:choose>
		<xsl:value-of select="$delimiter"/>
		
		<!-- EDSOF code: All items that are in the same Emergency Drug Supply exclusion group get the same code. -->
		<!-- The code is obtained by parsing the description field -->
		<!-- If a DB item is not a member of a EDS group then synthesize a value. This is a short-term measure. -->
		<xsl:variable name="group.eds" select="key('groups', $this/pbs:member-of-list/pbs:member-of/@xlink:href)[pbs:type = 'group:emergency-drug-supply']"/>
		<xsl:choose>
			<xsl:when test="$group.eds and
				contains($group.eds/pbs:description, '[')">
				<xsl:value-of select="substring-after($group.eds/pbs:description, '] = ')"/>
			</xsl:when>
			<xsl:when test="$this/ancestor::pbs:listings-list/pbs:info/pbs:code = 'DB'">
				<!-- Need to generate a unique code -->
				<xsl:value-of select="format-number(50 + count($this/preceding-sibling::pbs:prescribing-rule) + 1, '0000')"/>
			</xsl:when>
		</xsl:choose>
		<xsl:value-of select="$delimiter"/>
		
		<!-- Continued dispensing: 'Y' if continued dispensing applies to this item, 'N' otherwise -->
		<xsl:choose>
			<xsl:when test="$this/pbs:continued-dispensing">Y</xsl:when>
			<xsl:otherwise>N</xsl:otherwise>
		</xsl:choose>
		<xsl:value-of select='$end-of-line'/>
		
	</xsl:template>
	
	<xsl:template name="determineItemType">
		<xsl:param name="item" select="."/>
		
		<xsl:choose>
			<xsl:when test="$item/ancestor::pbs:listings-list/pbs:info/pbs:code = 'CI'">OD</xsl:when>
			<xsl:when test="$item/ancestor::pbs:listings-list/pbs:info/pbs:code = 'PQ'">PD</xsl:when>
			<xsl:when test="$item/pbs:extemporaneous-preparation">AP</xsl:when>
			<xsl:when test="$item/pbs:standard-formula-preparation">SF</xsl:when>
			<xsl:when test="$item/pbs:solvent-rule">SI</xsl:when>
			<xsl:when test="key('groups', key('mpps', $item/pbs:ready-prepared/pbs:mpp-reference/@xlink:href)/pbs:member-of-list/pbs:member-of/@xlink:href)[pbs:type = 'group:solvent']">RS</xsl:when> 
			<xsl:when test="key('groups', key('mpps', $item/pbs:ready-prepared/pbs:mpp-reference/@xlink:href)/pbs:member-of-list/pbs:member-of/@xlink:href)[pbs:type = 'group:solvent-required']">RI</xsl:when> 
			<xsl:when test="$item/pbs:ready-prepared">RP</xsl:when>
			<xsl:otherwise>
				<xsl:message terminate="no">Could not determine type for item <xsl:value-of select="$item/pbs:code"/> (id = <xsl:value-of select="@xml:id"/>)</xsl:message>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>
	
	<xsl:template name="determineCategoryCode">
		<xsl:param name="item" select="."/>
		
		<xsl:choose>
			<xsl:when test="starts-with(substring-after($item/descendant::pbs:classification/pbs:ATC, ':'), 'N06D')">AL</xsl:when>
			<xsl:when test="$item/ancestor::pbs:listings-list/pbs:info/pbs:code = 'CT'">CA</xsl:when>
			<xsl:when test="$item/ancestor::pbs:listings-list/pbs:info[pbs:code = 'TY' or pbs:code='TZ']">GL</xsl:when>
			<xsl:when test="$item/ancestor::pbs:listings-list/pbs:info/pbs:code = 'DB'">DB</xsl:when>
			<xsl:when test="key('groups', $item/pbs:member-of-list/pbs:member-of/@xlink:href)[pbs:type = 'group:premium-exemption'] and key('groups', $item/pbs:member-of-list/pbs:member-of/@xlink:href)[pbs:type = 'group:tgp']">TG</xsl:when>
			<xsl:when test="key('groups', $item/pbs:member-of-list/pbs:member-of/@xlink:href)[pbs:type = 'group:premium-exemption']">SP</xsl:when>
			<xsl:otherwise>
				<xsl:message terminate="no">Could not determine category code for item <xsl:value-of select="$item/pbs:code"/> (id = <xsl:value-of select="@xml:id"/>; program code = <xsl:value-of select="$item/ancestor::pbs:listings-list/pbs:info/pbs:code"/>)</xsl:message>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>
  
</xsl:stylesheet>